package ProxyTest;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @ClassName: PersonProxyBuiler
 * @Description: TODO(产生代理对象，类似retrofit接口类产生)
 * @author hsj
 * @email 2356899074@qq.com
 * @date 2019年6月25日
 *
 */
public class PersonProxyBuiler {

	@SuppressWarnings("unchecked")
	public static <T> T buid(Class<T> clazz) {
        
		// 代理实例
		return (T) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class<?>[] { clazz },
				new InvocationHandler() {//相当于重写InvocationHandler类
                    
			        //返回给用户设置回调接口类
			        private final CallBackQueue callBackQueue = new CallBackQueue();
			        
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						// System.out.println(proxy instanceof Person);
                         
						// 获取接口注解
						ProxyAnnotationTest aProxyAnnotationTest = method.getAnnotation(ProxyAnnotationTest.class);
						Annotation[][] aAnnotation = method.getParameterAnnotations();
						String url = aProxyAnnotationTest.value();
						String param = null;
						String paramValue = null;

						int i = 0;
						for (Annotation[] an1 : aAnnotation) {
							for (Annotation an2 : an1) {
								if (an2 instanceof ParamAnnotationTest) {
									ParamAnnotationTest aParamAnnotationTest = (ParamAnnotationTest) an2;
									param = aParamAnnotationTest.value();
									paramValue = (String) args[i++];
								}
							}
						}

						System.out.println("代理人操作获取ProxyAnnotationTest注解value=" + url);
						System.out.println("代理人操作获取ParamAnnotationTest注解value：" + param);
						System.out.println("代理人操作获取ParamAnnotationTest注解实际参数value：" + paramValue);
						//拼接参数
						String httpAll = url.replace("{" + param.trim() + "}", paramValue.trim());						
						
						//模拟耗时10s的请求操作执行
						new Thread(new Runnable() {
							
							@Override
							public void run() {
								try {
									System.out.println("代理人操作获取完整http请求httpAll地址：" + httpAll);
									System.out.println("代理人操作获取完整http请求httpAll,模拟http远程数据调用请求...耗时10s开始..." );
									TimeUnit.SECONDS.sleep(10);
									System.out.println("代理人操作获取完整http请求httpAll,模拟http远程数据调用请求...耗时10s结束...");
									//成功操作
									callBackQueue.callBackExecuteResponse("恭喜您，耗时10s执行远程http请求成功返回！");
									
								} catch (InterruptedException e) {
									e.printStackTrace();
								}							
							}
						}).start();
						
						
						return callBackQueue;
					}
				});
	}
}
